package com.aier.entrance.icsocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.eicp.ghostboy.futil.StringUtil;

import com.aier.common.common.Constant;
import com.aier.entrance.common.EntranceICFinalData;
import com.aier.entrance.common.EntranceServerData;
import com.aier.entrance.entity.EntranceDevice;
import com.aier.entrance.entity.VideoDevice;
import com.aier.entrance.service.IEntranceCardService;
import com.aier.entrance.service.Snapshot;

public class EntranceSendCommand {
    static final int cardNo = 12;                                    //写入卡号的起始ID
    String ip;
    String sn;
    Map<String,String> snMap = new HashMap<String,String>();
    int port;
    Socket s;
    private IEntranceCardService ec;
    public EntranceSendCommand(Socket s,String ip,String sn,int port,IEntranceCardService ec){
        this.s = s;
        this.ip = ip;
        this.sn = sn;
        this.port = port;
        this.ec = ec;
    }
    
    /**
     * @param state 需要执行的操作，1--开门，2--门常开，3--关门，4--开报警，5--关报警，6--开火警，7--关火警，
     *                              8--单门增加卡，9--双门增加卡，10--四门增加卡，11--批量增加卡 12--清除所有卡指令
     *                              13--控制器复位指令 ,  14--删除一张卡指令
     * @param ip    设备的ip地址
     * @param sn    设备的序列号
     * @param pont  设备的端口
     * @return        执行之后的结果   -1表示失败，1表示成功
     */
    public int exeEU(int state){
        String com = "";                              //命令格式
        String[] data = null;                        //数据部分
        String lengthL = "";                        //数据长度地位
        String lengthH = "";                        //数据长度高位
        int answer = -1;                            //设备回应                            
    
        switch(state){
            case 1:            {                        //如果为开门指令
                com = "2c";
                lengthL = "01";
                lengthH = "00";
                data = new String[]{"00"};
                break;        
            }
            case 2:        {                        //门常开指令
                com = "2d";
                lengthL = "01";
                lengthH = "00";
                data = new String[]{"00"};
                break;
            }        
            case Constant.num_3:{                                //关门指令
                com = "2e";
                lengthL = "01";
                lengthH = "00";
                data = new String[]{"00"};
                break;
            }            
            case Constant.num_4:{                                //开报警指令
                com = "18";
                lengthL = "02";
                lengthH = "00";
                data = new String[]{"00","00"};
                break;
            }        
            case Constant.num_5:{                                //关报警指令
                com = "18";
                lengthL = "02";
                lengthH = "00";
                data = new String[]{"01","00"};
                break;
            }            
            case Constant.num_6:{                                //开火警指令
                com = "19";
                lengthL = "02";
                lengthH = "00";
                data = new String[]{"00","00"};
                break;
            }            
            case Constant.num_7:{                                //关火警指令
                com = "19";
                lengthL = "02";
                lengthH = "00";
                data = new String[]{"01","00"};
                break;
            }            
            case Constant.num_8:{                                //单门增加卡指令
                com = "62";
                lengthL = "11";
                lengthH = "00";
                data = new String[]{"64","00","0a","e6","91","00","13","45","05","00","00","00","0d","04","12","01","00"};
                break;
            }            
            case Constant.num_9:{                                //双门增加卡指令
                com = "62";
                lengthL = "11";
                lengthH = "00";
                data = new String[]{"00","05","00","48","a4","bd","22","22","02","00","02","00","0d","03","07","00","00"};
                break;
            }            
            case Constant.num_10:{                                //四门增加卡指令
                com = "62";
                lengthL = "11";
                lengthH = "00";
                data = new String[]{"02","00","d2","9a","67","00","22","22","02","03","01","03","0c","01","07","00","00"};
                break;
            }            
            case Constant.num_11:{                                //批量增加卡
                com = "88";
                lengthL = "24";
                lengthH = "00";
                data = new String[]{"06","00","02","96","00",
                    "97","00","00","00","12","34","02","03","01","03","9b","0c","1e","00","00",
                    "98","00","00","00","12","34","02","03","01","03","9b","0c","1e","00","00",
                    "8c"
                };
                break;            
            }    
            case Constant.num_12:{                                //清除所有卡操作
                com = "17";
                lengthL = "00";
                lengthH = "00";
                break;
            }
            case Constant.num_13:{                                //复位操作
                com = "04";
                lengthL = "00";
                lengthH = "00";
                break;
            }
            case Constant.num_14:{    
                
                /*//删除一张卡指令
                com = "16";
                lengthL = "06";
                lengthH = "00";
                data = new String[]{"5c","00","00","00","00","00"};
                */
                /*
                com = "62";
                lengthL = "11";
                lengthH = "00";
                data = new String[]{"62","00","00","00","00","00","00","00",
                        "01","01","00","00","00","00","00","00","00"};
                        */
            }
            default:{
                break;
            }            
        }
        if(s != null){
            answer = sendCommand(s ,com ,lengthL ,lengthH ,data);
        }
        
        return answer;
    } 
    
    /**
     * @param com        
     * @param lengthL
     * @param lengthH
     * @param data
     * @return        返回指令是否发送成功 1表示成功，-1表示失败
     */
    public int sendCommand(Socket s,String com,String lengthL,String lengthH,String[] data){
        String command = "";
        int answer = -1;
        //获得命令格式
        command = getCommand(com, lengthL, lengthH, data);
        //System.out.println("指令" + command);            
        new SenderThread(s, command).start();        
        
        return answer;    
    }
    
    
    /**
     * @param com        命令
     * @param lengthL   
     * @param lengthH
     * @param data        数据位
     * @return    得到完整的指令
     */
    public String getCommand(String com,String lengthL,String lengthH,String[] data){
        final String stxAndRand = "02 a0";        //开始位和随机数
        final String addAndDoor = "ff 00";        //地址和门号    
        final String end = "03";                //结束位
        String cs = "";                            //校验值            
        String command = "";                    //指令
        String dataStr = "";                    //data字符串        
        //02与a0进行异或，则为a2;ff与00 异或则为ff;
        cs = getXorBystr("a2", com);
        cs = getXorBystr(cs, "ff");
        cs = getXorBystr(cs, lengthL);
        cs = getXorBystr(cs, lengthH);
        if(data != null){
            for (int i = 0; i < data.length; i++) {
                dataStr += data[i] + " ";
                cs = getXorBystr(cs, data[i]);
            }
        }
        command = stxAndRand + " " + com + " " + addAndDoor + " " + lengthL + " " + lengthH + " " + dataStr
                + cs + " " + end;
        
        
        return command;        
    }
    
    /**
     * 进行异或操作，得到所需的值
     * @param a        参数a
     * @param b        参数b
     * @return
     */
    public  String getXorBystr(String a, String b){
        String result = "";
        String a1 = a.substring(0, 1);    
        String a2 = a.substring(1, 2);
        String b1 = b.substring(0, 1);    
        String b2 = b.substring(1, 2);

        int a1A = getArrayFromStr(a1);
        int a2A = getArrayFromStr(a2);
        int b1A = getArrayFromStr(b1);
        int b2A = getArrayFromStr(b2);
        
        int con = a1A^b1A;
        if(con > Constant.num_9) {result = (char)((con - Constant.num_10) + 'a') + "";}
        else {result = con + "";}
        con = a2A^b2A;
        if(con > Constant.num_9) {result = result + (char)((con - Constant.num_10) + 'a');}
        else {result = result + con;}
        return result;        
    }
    
    /**
     * 
     * @param str
     * @return 字符数组
     */
    public int getArrayFromStr(String str){
        int arr = -1;
        if(str.equals("0")){
            arr = 0;
        }else if(str.equals("1")){
            arr = 1;
        }else if(str.equals("2")){
            arr = 2;
        }else if(str.equals("3")){
            arr = Constant.num_3;
        }else if(str.equals("4")){
            arr = Constant.num_4;
        }else if(str.equals("5")){
            arr = Constant.num_5;
        }else if(str.equals("6")){
            arr = Constant.num_6;
        }else if(str.equals("7")){
            arr = Constant.num_7;
        }else if(str.equals("8")){
            arr = Constant.num_8;
        }else if(str.equals("9")){
            arr = Constant.num_9;
        }else if(str.equals("a")){
            arr = Constant.num_10;
        }else if(str.equals("b")){
            arr = Constant.num_11;
        }else if(str.equals("c")){
            arr = Constant.num_12;
        }else if(str.equals("d")){
            arr = Constant.num_13;
        }else if(str.equals("e")){
            arr = Constant.num_14;
        }else if(str.equals("f")){
            arr = Constant.num_15;
        }
        return arr;    
    }
    
    /**
     * 整形转换成字符型数据
     * @param i需要转换的整形
     * @return 返回字符型数据
     */
    public  byte[] intToByteArray1(int i) {   
        byte[] result = new byte[Constant.num_4];   
        result[0] = (byte)((i >> Constant.num_24) & Constant.num_ff);
        result[1] = (byte)((i >> Constant.num_16) & Constant.num_ff);
        result[2] = (byte)((i >> Constant.num_8) & Constant.num_ff); 
        result[Constant.num_3] = (byte)(i & Constant.num_ff);
        return result;
    }

    
    /**
     * 接收从设备发送过来的信息
     * @param s
     * @return  返回字符串数组
     */
    
    public class receiveMsgFromDev implements Runnable{
        Socket s;
        InputStream in;
        Thread t;
        public receiveMsgFromDev(Socket s){
            this.s = s;
            try {
                in = s.getInputStream();
                t = new Thread(this);
                t.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        @Override
        public void run() {
            try {            
                //输出监听内容
                byte[] bs = new byte[Constant.num_1024];
                int len;
                String result = null;
                String threadID;
                String mapContent;
                while(true){
                    len = in.read(bs);
                    byte[] a = new byte[len];
                    System.arraycopy(bs, 0, a, 0, len);
                    result = doWithStr(a); 
                    System.out.println("上传开始时间" + new Date().getTime());
                    //获取应答位
                    String com = result.substring(Constant.num_6,Constant.num_8);
                    @SuppressWarnings("unused")
                    String isMore = null;                                    //是否还有记录
                    String curnum = null;                                    //当前的记录号
                    String sn = null;                                        //设备序列号
                    String command = null;                                    //命令格式
                    String[] cardNoArray = null;                            //卡号数组
                    String type = null;                                        //状态类型
                    int cardNo;
                    long[] flag =new long[]{-1};                            //调用服务器数据库之后的结果                                                
                    EntranceDevice ed;
                    //VideoDevice vd;
                    if(com.equals("53")){                                    //刷卡记录回应    
                        //卡号
                        cardNoArray = result.substring(Constant.num_21, Constant.num_32).split(" ");
                        //System.out.println(cardNoArray[0] + cardNoArray[1] + cardNoArray[2] + cardNoArray[3]);
                        cardNo = (int) getNoFromHexString(cardNoArray);
                        //获取门状态信息
                        type = result.substring(Constant.num_51, Constant.num_53);
                        if(type.equals("01")){                                //无效卡
                            //如果是无效卡，则马上写入控制器并进行开门指令
                            flag = ec.updateSwingICCard(snMap.get(Thread.currentThread().getId() + ""),cardNo + "",
                                    IEntranceCardService.OPERATE_IN,null);
                            if((flag[0] != EntranceICFinalData.SWINGICCARD_STATE_USER_SUCCESS)&&
                                    (flag[0] != EntranceICFinalData.SWINGICCARD_STATE_TEACHER_SUCCESS)
                                    	&&(flag[0] != EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS)){
                                //报警
                                doWarning();
                            }
                        }else if(type.equals("0b")){                        //进门事件                            
                            //调用服务器的操作
        //                    System.out.println("刷完卡之前时间" + new Date().getTime());
                            flag = ec.updateSwingICCard(snMap.get(Thread.currentThread().getId() + ""),cardNo + "",
                                    IEntranceCardService.OPERATE_IN,null);
        //                    System.out.println("服务器响应" + flag[0] + "-->" + getResultFromServerLong(flag[0]));
                            if((flag[0] == EntranceICFinalData.SWINGICCARD_STATE_USER_SUCCESS)||
                                    (flag[0] == EntranceICFinalData.SWINGICCARD_STATE_TEACHER_SUCCESS)){
                                
                                //拍照操作
                                ed =EntranceServerData.mapED.get(snMap.get(Thread.currentThread().getId() + ""));
                                if((EntranceICFinalData.ENTRANCE_VDSTATE_ALL == ed.getVdstate()) || 
                                        (EntranceICFinalData.ENTRANCE_VDSTATE_IN == ed.getVdstate())){
                                    //vd= ed.getVd();
                                    //Snapshot.snap(vd.getUrl(),vd.getUser(),vd.getPwd(), flag[1]);
                                    
        //                            System.out.println("拍照之前时间" + new Date().getTime());
                                    doSnap(ed,ec.updateImg(flag[2], flag[1],flag[0], IEntranceCardService.OPERATE_IN));
                                }
                                
                                //command = getCommand("2c", "01", "00", new String[]{"01"});
                                //new SenderThread(s, command).start();
                            }else if(flag[0] != EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                                //报警
                                doWarning();
                            }
                        }else if(type.equals("0a")){                        //出门事件
                            
                            flag = ec.updateSwingICCard(snMap.get(Thread.currentThread().getId() + ""),
                                    cardNo + "",IEntranceCardService.OPERATE_OUT,null);
                            if((flag[0] == EntranceICFinalData.SWINGICCARD_STATE_USER_SUCCESS)||
                                    (flag[0] == EntranceICFinalData.SWINGICCARD_STATE_TEACHER_SUCCESS)){
                                
                                //拍照操作
                                ed =EntranceServerData.mapED.get(snMap.get(Thread.currentThread().getId() + ""));
                                if((EntranceICFinalData.ENTRANCE_VDSTATE_ALL == ed.getVdstate()) || 
                                        (EntranceICFinalData.ENTRANCE_VDSTATE_OUT == ed.getVdstate())){
                                    //vd= ed.getVd();
                                    //Snapshot.snap(vd.getUrl(),vd.getUser(),vd.getPwd(), flag[1])
                                    doSnap(ed,ec.updateImg(flag[2], flag[1],flag[0],IEntranceCardService.OPERATE_OUT));
                                }
                                
                            //command = getCommand("2e", "01", "00", new String[]{"01"});
                            //new SenderThread(s, command).start();
                            }else if(flag[0] != EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                                doWarning();
                            }
                        }
//                        else if(type.equals("03")){                        //无效开放时间
//                            System.out.println("无效开放时间");
//                        }
                        //还有记录，则必须回应
                        isMore = result.substring(Constant.num_57, Constant.num_59);
                        curnum = result.substring(Constant.num_60, Constant.num_62);
                        sendCommand(s, com, "01", "00", new String[]{curnum});
                        

                    }else if(com.equals("54")){                                            //报警记录回应
                        isMore = result.substring(Constant.num_45, Constant.num_47);
                        curnum = result.substring(Constant.num_48, Constant.num_50);
                        sendCommand(s, com, "01", "00", new String[]{curnum});
                    }else if(com.equals("56")){                                            //状态回应
                        //设备号 
                        sn = result.substring(Constant.num_85,Constant.num_86) + result.substring(Constant.num_88,Constant.num_89) + 
                             result.substring(Constant.num_91,Constant.num_92) + result.substring(Constant.num_94,Constant.num_95) +
                             result.substring(Constant.num_97,Constant.num_98) + result.substring(Constant.num_100,Constant.num_101);
                        threadID = Thread.currentThread().getId() + "";
                        mapContent = snMap.get(threadID);
                        if((null == mapContent) || ("".equals(mapContent))){ 
                            //遍历map,清除相同value的键值对
                            snMap = removeSameValueFromMap(snMap, sn);
                            snMap.put(threadID, sn);
                        }
                        sendCommand(s, com, "02", "00", new String[]{"00","00"});
                    
                    }else if(com.equals("17")){
                        
                        for(int j = 0; j < 1; j++){
                            String[] cardID = getCardID(j);
                            command = getCommand("62", "11", "00", 
                                    new String[]{cardID[0],cardID[1],"00","00","00","00","00","00","00","00","00","00","00","00","00","00","00"});
                            new SenderThread(s, command).start();
                            Thread.sleep(Constant.num_50);
                        }
                        
                    }
//                    else if(com.equals("2c")){                                                    
//        //                String answer = result.substring(21,23);
//        //                if(answer.equals("06")) System.out.println("设备" + snMap.get(Thread.currentThread().getId() + "") + "开门");    
//                    }else if(com.equals("2d")){
//        //                String answer = result.substring(21,23);
//        //                if(answer.equals("06")) System.out.println("设备" + snMap.get(Thread.currentThread().getId() + "") + "门常开");    
//                    }else if(com.equals("2e")){
//        //                String answer = result.substring(21,23);
//        //                if(answer.equals("06")) System.out.println("设备" + snMap.get(Thread.currentThread().getId() + "") + "关门");    
//                    }else if(com.equals("62")){
//        //                String answer = result.substring(21,23);
//        //                if(answer.equals("06")) System.out.println("设备" + snMap.get(Thread.currentThread().getId() + "")+ "写卡成功");    
//                    }
                    
                    System.out.println("上传结束时间" + new Date().getTime());
                    
                }                
                //in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 进行报警操作
     * @throws InterruptedException
     */
    public void doWarning() throws InterruptedException{
        String command;
        //如果打卡不成功,则报警
        command = getCommand("18", "02", "00", new String[]{"00","00"});
        new SenderThread(s, command).start();
        //报警1.5秒钟
        Thread.sleep(Constant.num_1200);
        command = getCommand("18", "02", "00", new String[]{"01","00"});
        new SenderThread(s, command).start();
    }
    
    /**
     * 进行拍照操作
     */
    public void doSnap(EntranceDevice ed,String filepath){
        VideoDevice vd= ed.getVd();
        URL u;
        String url = "";
        String user = "";
        String pwd = "";
        short supplier;
        System.out.println("解析开始时间" + new Date().getTime());
        try {
            u = new URL(vd.getUrl());
            URLConnection uc = u.openConnection();
            uc.getContentType();
            url = uc.getURL().toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("解析结束时间" + new Date().getTime());

        user = vd.getUser();
        pwd = vd.getPwd();
        supplier = vd.getSupplier();
        if(null == pwd){ 
            pwd = "";
        }
        if((!"".equals(url))&&(!StringUtil.isStringNull(filepath))){
            new Snapshot(supplier,url, user, pwd,filepath).start();
        }
        
       
    }
    
    /**
     * 
     * @param map    存放以 线程ID为key，设备号为content的键值对
     * @param sn    设备号    
     * @return        删除相同value的之前存放的键值对
     */    
    public Map<String,String> removeSameValueFromMap(Map<String,String> map,String sn){
        Set<String> set = map.keySet();
    
        //遍历map
        for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
            String key = iterator.next();
            String value = map.get(key);
            if(value == sn) {map.remove(key);}
        }
        return map;
        
    }
    
    
    /**
     * 
     * @param flag 服务器返回的结果
     * @return    整型结果对应的数据
     */
    public String getResultFromServerLong(long flag){
        String result;
        if(flag == 0) {result = "打卡失败";}
        else if(flag == 1) {result = "无该设备";}
        else if(flag == 2) {result = "该设备停用状态";}
        else if(flag == Constant.num_3) {result = "卡不存在或停用";}
        else if(flag == Constant.num_4) {result = "用户无权限在该设备上打卡";}
        else if(flag == Constant.num_5) {result = "用户记录失败";}
        else if(flag == Constant.num_10) {result = "用户记录成功";}
        else if(flag == Constant.num_20) {result = "教师打卡记录成功";}
        else {result = "操作失败";}
        return result;
        
    }

    /**
     * 
     * @param n         整型序号
     * @return            返回16进制的序号
     */
    public String[] getCardID(int n){
        String[] CardID = new String[2];

        String s = null;
        if(n<=Constant.num_256){
            int n1 = n/Constant.num_16;
            int n2 = n%Constant.num_16;
            s = getHexFromInt(n1) + getHexFromInt(n2);
            CardID[0] = s;
            CardID[1] = "00";
        }else{
            int m1 = n%Constant.num_256;
            int m2 = m1/Constant.num_16;            
            int m3 = m1%Constant.num_16;
            s = getHexFromInt(m2) + getHexFromInt(m3);
            CardID[0] = s;
            int m4 = n/Constant.num_256;
            int m5 = m4/Constant.num_16;
            int m6 = m4%Constant.num_16;
            s = getHexFromInt(m5) + getHexFromInt(m6);
            CardID[1] = s;
        }

        System.out.println("序号" + CardID[0] + CardID[1]);
        return CardID;
        
    }
    
    /**
     * 
     * @param n 10进制整数
     * @return    16进制
     */
    public String getHexFromInt(int n){
        String result = "";
        if(n > Constant.num_9) {result = (char)((n - Constant.num_10) + 'a') + "";}
        else {result = n + "";}
        return result;
    }

    
    
    /**
     * 
     * @param a    经过加密的16进制
     * @return    卡号
     */
    public long getNoFromHexString(String[] a){
        int n;
        int m;
        int num;
        int[] no = new int[Constant.num_4];
        for (int i = a.length-1,j=0; i >= 0; i--,j++) {
            n = getArrayFromStr(a[i].substring(0, 1));
            m = getArrayFromStr(a[i].substring(1, 2));
            num = n*Constant.num_16 + m;
            if(num > Constant.num_127) {no[j] = num - Constant.num_256;}
            else {no[j] = num;}
        }
        
        byte[] b = new byte[]{(byte)no[0],(byte)no[1],(byte)no[2],(byte)no[Constant.num_3]};
        long value= 0;
        for (int i = 0; i < Constant.num_4; i++) {
            int shift= (Constant.num_4 - 1 - i) * Constant.num_8;
            value +=(b[i + 0] & Constant.num_000000ff) << shift;//往高位游
        }
        
        return value;
        
    }
    
    /**
     * 转码
     * @param bArray
     * @return  返回二进制数据
     */
    public String doWithStr(byte[] bArray){
        
        //转码
        StringBuffer strb = new StringBuffer(bArray.length);
        String str;
        
        for(int i=0; i<bArray.length; i++){
            str = Integer.toHexString(Constant.num_ff & bArray[i]).trim();
            if (str.length() < 2) {
                str = "0" + str;
            }
            str += " ";
            strb.append(str);
        }
        return strb.toString();
    }
    
    /**
     * 判断命令是否发送正确
     * @param str
     * @return   1--表示成功,-1--表示失败
     */
    public int isRight(String[] str){
        int i=0;
        int state = -1;
        while(null!=str[i] && !"".equals(str[i])){
            //获取单条信息
            String onestr = str[i];
            //获取单条信息的长度
            int length = onestr.length();
            if((length >= Constant.num_29) && (length < Constant.num_86)){
                String answer = onestr.substring(Constant.num_21,Constant.num_23);
                if(answer.equals("06")) {state = 1;}                    
            }
            i++;
        }
        return state;
        
    }
    
    
    
}


/**
 *     向设备发送信息的线程
 * @author Administrator
 *
 */
class SenderThread extends Thread{
    Socket s;
    String command = "";
    public SenderThread(Socket s,String command){
        this.s = s;
        this.command = command;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    
        try {
            OutputStream out = s.getOutputStream();
            if(!"".equals(command)){
                //System.out.println(command);
                //byte[] com = command.getBytes();
                byte[] com = hexStrToByte(command);
                /*
                for (int i = 0; i < com.length; i++) {
                    System.out.print(com[i]);
                }
                */
                //System.out.println(com.toString());
                
                out.write(com);
                out.flush();
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            
        }
    
    }
    //加密
    public byte[] hexStrToByte(String context) {
        ArrayList<String> list = new ArrayList<String>();
        String str = "";
        String[] strs = null;
        if (context.indexOf(" ") != -1) {
            strs = context.split(" ");
            list.addAll(Arrays.asList(strs));
        } else {
            for (int i = 0; i < context.length() / 2; i++) {
                str = context.substring(i * 2, i * 2 + 2);
                list.add(str);
            }
        }
        //logger.debug("\r\t hexStrtoByte:" + list.toString());
        byte[] b = new byte[list.size()];
        try {
            for (int i = 0; i < b.length; i++) {
                b[i] = Integer.valueOf(list.get(i).toString(), Constant.num_16).byteValue();
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return b;
    }    
}